package com.glory.hikvisionmobile.activity;

import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.hikvisionmobile.R;
import com.glory.hikvisionmobile.adapter.WorkThingListAdapter;
import com.glory.hikvisionmobile.base.BaseActivity;
import com.glory.hikvisionmobile.bean.net.BaseResponseBean;
import com.glory.hikvisionmobile.bean.search.WorkThingBaseBean;
import com.glory.hikvisionmobile.bean.search.WorkThingBean;
import com.glory.hikvisionmobile.utils.EditTextEnterUtils;
import com.glory.hikvisionmobile.utils.NetUtils;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.datepicker.CustomDatePicker;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DateUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class Lot_SearchWorkThingActivity extends BaseActivity {

    @BindView(R.id.tvLotType)
    TextView tvLotType;
    @BindView(R.id.ivLotTypeListArrow)
    ImageView ivLotTypeListArrow;
    @BindView(R.id.flLotTypeList)
    FrameLayout flLotTypeList;
    @BindView(R.id.etProduction)
    EditText etProduction;
    @BindView(R.id.tvWorking)
    TextView tvWorking;
    @BindView(R.id.ivWorkingListArrow)
    ImageView ivWorkingListArrow;
    @BindView(R.id.flWorkingList)
    FrameLayout flWorkingList;
    @BindView(R.id.tvSearch)
    TextView tvSearch;
    @BindView(R.id.rvSearchWorkThingList)
    RecyclerView rvSearchWorkThingList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.etWorkNum)
    FreeUI_ClearEditText etWorkNum;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.tvPause)
    TextView tvPause;
    @BindView(R.id.ivPauseListArrow)
    ImageView ivPauseListArrow;
    @BindView(R.id.flPauseList)
    FrameLayout flPauseList;
    @BindView(R.id.tvStatus)
    TextView tvStatus;
    @BindView(R.id.tvClearBegin)
    TextView tvClearBegin;
    @BindView(R.id.tvClearEnd)
    TextView tvClearEnd;
    @BindView(R.id.ivStatusListArrow)
    ImageView ivStatusListArrow;
    @BindView(R.id.flStatusList)
    FrameLayout flStatusList;
    @BindView(R.id.tvBeginTime)
    TextView tvBeginTime;
    @BindView(R.id.ivBeginTimeArrow)
    ImageView ivBeginTimeArrow;
    @BindView(R.id.flBeginTimeList)
    FrameLayout flBeginTimeList;
    @BindView(R.id.tvEndTime)
    TextView tvEndTime;
    @BindView(R.id.ivEndTimeArrow)
    ImageView ivEndTimeArrow;
    @BindView(R.id.flEndTimeList)
    FrameLayout flEndTimeList;
    @BindView(R.id.list_titleLayout)
    LinearLayout listTitleLayout;
    @BindView(R.id.nsScroll)
    NestedScrollView nsScroll;

    private FreeUI_GeneralPop lotTypePop;
    private String lotType;
    private FreeUI_GeneralPop statusPop;
    private String status;
    private FreeUI_GeneralPop partPop;
    private String partName;
    private FreeUI_GeneralPop pausePop;
    private String pauseCode;
    private CustomDatePicker mDatePicker;
    private String beginDate;
    private String endDate;
    boolean isBegin;
    private int position = 1;
    private WorkThingListAdapter workThingListAdapter;
    private List<WorkThingBean> data = new ArrayList<>();
    private List<String> partList = new ArrayList<>();


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_search_work_thing;
    }

    @Override
    protected void initView() {
        initDatePicker();
        rvSearchWorkThingList.setLayoutManager(new LinearLayoutManager(Lot_SearchWorkThingActivity.this));
        rvSearchWorkThingList.setItemAnimator(new DefaultItemAnimator());
        rvSearchWorkThingList.addItemDecoration(new DividerItemDecoration(Lot_SearchWorkThingActivity.this, 1));
        workThingListAdapter = new WorkThingListAdapter(data);
        workThingListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        workThingListAdapter.isFirstOnly(true);
        rvSearchWorkThingList.setAdapter(workThingListAdapter);
        EditTextEnterUtils.initEnterToUpperCase(etLot);
        rvSearchWorkThingList.setOnScrollChangeListener((view, i, i1, i2, i3) -> {
            if (!rvSearchWorkThingList.canScrollVertically(1)) {
                if (!rvSearchWorkThingList.canScrollVertically(-1)){
                    return;
                }
                if (position > 1){
                    search();
                }

            }
        });
    }

    private void initDatePicker() {
        long beginTimestamp = FreeApi_DateUtils.str2Long("1992-03-20", false);
        long endTimestamp = FreeApi_DateUtils.str2Long("2222-02-22", false);

        // 通过时间戳初始化日期，毫秒级别
        mDatePicker = new CustomDatePicker(this, timestamp -> {
            if (isBegin) {
                beginDate = FreeApi_DateUtils.long2Str(timestamp, false);
                tvBeginTime.setText(beginDate);
            } else {
                endDate = FreeApi_DateUtils.long2Str(timestamp, false);
                tvEndTime.setText(endDate);
            }

        }, beginTimestamp, endTimestamp);
        // 不允许点击屏幕或物理返回键关闭
        mDatePicker.setCancelable(true);
        // 不显示时和分
        mDatePicker.setCanShowPreciseTime(false);
        // 不允许循环滚动
        mDatePicker.setScrollLoop(false);
        // 不允许滚动动画
        mDatePicker.setCanShowAnim(false);
    }

    @Override
    protected void initData() {
        //批次类型
        NetUtils.getLotTypeList("LotType", "USER", this, getSupportFragmentManager(), new NetUtils.SelectorCallback() {
            @Override
            public void onSuccess(List<String> list) {
                list.add(0,"");
                if (lotTypePop == null) {
                    lotTypePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flLotTypeList.getWidth(), list, ivLotTypeListArrow, (codeS, i) -> {
                        tvLotType.setText(codeS);
                        String[] split = codeS.split("/");
                        lotType = split[split.length - 1];
                    });

                }
            }

            @Override
            public void onFail(Throwable e, String messageName) {
                loadError(e, messageName);
            }
        });
        //状态大类
        NetUtils.getSelectorList("LotComClass", "SYS", this, getSupportFragmentManager(), new NetUtils.SelectorCallback() {
            @Override
            public void onSuccess(List<String> list) {
                list.add(0,"");
                if (statusPop == null) {
                    statusPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flStatusList.getWidth(), list, ivStatusListArrow, (codeS, i) -> {
                        tvStatus.setText(codeS);
                        status = codeS.split("/")[0];
                    });

                }
            }

            @Override
            public void onFail(Throwable e, String messageName) {
                loadError(e, messageName);
            }
        });

        NetUtils.getPartSelectorList(this, getSupportFragmentManager(), new NetUtils.SelectorCallback() {
            @Override
            public void onSuccess(List<String> list) {
                partList.add(0,"");
                partList.addAll(list);
            }

            @Override
            public void onFail(Throwable e, String messageName) {
                loadError(e, messageName);
            }
        });

    }

    private List<String> getPauseCode() {
        List<String> pauseData = new ArrayList<>();
        pauseData.add(0,"");
        pauseData.add("On");
        pauseData.add("Off");
        return pauseData;
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("在制品查询");
        freeUI_titleView.setRightListener("隐藏", view -> {
            initPermission("Refresh", this, new ActionControlListener() {
                @Override
                public void onControlChangeListener() {
                    nsScroll.setVisibility(nsScroll.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE);
                }
            });
        });
        return new FreeUI_AddViewEntity("header", llMain);
    }

    @OnClick({R.id.tvSearch,R.id.flLotTypeList, R.id.flWorkingList, R.id.flPauseList, R.id.flStatusList, R.id.flBeginTimeList, R.id.flEndTimeList,R.id.tvClearBegin,R.id.tvClearEnd})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvClearBegin:
                tvBeginTime.setText("");
                beginDate = "";
                break;
            case R.id.tvClearEnd:
                tvEndTime.setText("");
                endDate = "";
                break;
            case R.id.tvSearch:
                initPermission("Search", this, new ActionControlListener() {
                    @Override
                    public void onControlChangeListener() {
                        data.clear();
                        position = 1;
                        workThingListAdapter.notifyDataSetChanged();
                        search();
                    }
                });
                break;
            case R.id.flLotTypeList:
                showPopWindow(lotTypePop,"未请求到批次类型列表",ivLotTypeListArrow,flLotTypeList);
                break;
            case R.id.flWorkingList:
                //产品
                if (partPop == null) {
                    partPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flWorkingList.getWidth(), partList, ivWorkingListArrow, (codeS, i) -> {
                        tvWorking.setText(codeS);
                        partName = codeS.split("/")[0];
                    });

                }else {
                    showPopWindow(partPop,"未请求到产品列表",ivWorkingListArrow,flWorkingList);
                }
                break;
            case R.id.flPauseList:
                //暂停状态
                if (pausePop == null) {
                    pausePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flPauseList.getWidth(), getPauseCode(), ivPauseListArrow, (codeS, i) -> {
                        tvPause.setText(codeS);
                        pauseCode = codeS;
                    });
                }else {
                    showPopWindow(pausePop,"",ivPauseListArrow,flPauseList);
                }
                break;
            case R.id.flStatusList:
                showPopWindow(statusPop,"未请求到状态大类列表",ivStatusListArrow,flStatusList);
                break;
            case R.id.flBeginTimeList:
                isBegin = true;
                mDatePicker.show(System.currentTimeMillis());
                break;
            case R.id.flEndTimeList:
                isBegin = false;
                mDatePicker.show(System.currentTimeMillis());
                break;
        }
    }

    private void search() {
        JsonObject map = new JsonObject();
        map.addProperty("woId",etWorkNum.getText().toString().trim());
        map.addProperty("lotId",etLot.getText().toString().trim());
        map.addProperty("holdState",pauseCode);
        map.addProperty("partName",partName);
        map.addProperty("stageId",etProduction.getText().toString().trim());
        map.addProperty("lotType",lotType);
        map.addProperty("comClass",status);
        map.addProperty("pageSize","20");
        map.addProperty("pageNo",position);
        map.addProperty("fromStartTime",beginDate);
        map.addProperty("toStartTime",endDate);
        NetUtils.requestDara("HIK.PdaWipQuery", this, map, new FreeUI_DialogEntityCallBack<BaseResponseBean<WorkThingBaseBean>>(
                new TypeToken<BaseResponseBean<WorkThingBaseBean>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<WorkThingBaseBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    WorkThingBaseBean workThingBaseBean = response.body().getBody();
                    if (workThingBaseBean.getXPdaLots().size() <= 0){
                        showToast("当前没有更多数据",false);
                    }else {
                        nsScroll.setVisibility(View.GONE);
                        position += 1;
                        workThingListAdapter.addData(workThingBaseBean.getXPdaLots());
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<WorkThingBaseBean>> response) {
                super.onError(response);
                loadError(response.getException(), "HIK.PdaWipQuery");
            }
        });


    }

    private void showPopWindow(FreeUI_GeneralPop popName,String message,ImageView icon,FrameLayout flLayout){
        if (popName == null) {
            showToast(message, false);
            return;
        }
        if (popName.isShowing()) {
            popName.dismiss();
        } else {
            FreeApi_PopUtils.setArrowShow(icon);
            popName.showAsDropDown(flLayout, 0, 0);
        }
    }
}
